from webargs import fields

from webutils.marshmallow.validate import LengthValidator
from webutils.webargs.bare import use_args
from .. import const, params, services


class CounterMixin:
    @use_args({
        'from': params.Sender(required=True),
        'data':
        fields.Nested({
            'key': fields.Str(required=True, validate=LengthValidator(0, 50)),
        }),
    })  # yapf: disable
    async def on_act_counter(self, args, conn):
        user_id, user_name = args['from']['id'], args['from']['name']
        key = args['data']['key']
        counter = services.Counter(
            conn,
            room_id=self.session.room_id,
            counter_id=key,
        )
        total = await counter.add(user_id)

        message = {
            'act': str(const.ActType.COUNTER.value),
            'from': f'{user_id}:{user_name}',
            'data': {
                'key': args['data']['key'],
                'total': total,
            }
        }
        await self.broadcaster_app.send_task(
            'broadcast_counter',
            message,
            group=const.UserGroup.ALL,
        )
